package main

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"

	"github.com/skip2/go-qrcode"
)

func Md5(arg ...any) []byte {
	h := md5.New()
	h.Write([]byte(fmt.Sprint(arg)))
	return h.Sum(nil)
}

func readFile(fileName string) []byte {
	fi, err := os.Open(fileName)
	if err != nil {
		fmt.Fprintln(os.Stderr, fileName, err)
		return nil
	}
	defer fi.Close()
	buff, _ := ioutil.ReadAll(fi)
	return buff
}

func outFile(fileName string, outFileBytes []byte) {
	fi, err := os.Create(fileName)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
	fi.Write(outFileBytes)
	fi.Close()
}

func outQrcodePng(src string) []byte {
	buff, err := qrcode.Encode(src, qrcode.Medium, 320)
	if err != nil {
		fmt.Errorf("qrcode.Encode src=%v err=%v", src, err)
		return nil
	}

	return buff
}

func outQrcodeBase64(src string) string {
	qr := outQrcodePng(src) // http://192.168.1.101:8080/score?key=asdfasdf
	return base64.StdEncoding.EncodeToString(qr)
}

func getClientIP(r *http.Request) string {
	// RemoteAddr 格式通常是 "IP:port"
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return "" // 或者返回 r.RemoteAddr，取决于你的需求
	}
	return host
}
